import React, { useRef, useState, useEffect } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { Popconfirm, message, Upload, Button, Select, Form, Switch, Tag, Typography, InputNumber} from 'antd';
import { delOSType, delKernelVersion, getOSTypeList, getKernelVersionList, submitOSType, submitKernelVersion, postChangeOsType, PostWhetherSyncRequest } from '../../service';
import { ProForm, ModalForm, ProFormText, ProFormTextArea, ProFormSelect, ProFormSwitch } from '@ant-design/pro-form';
import { async } from '@antv/x6/lib/registry/marker/async';
import { PropertySafetyFilled, DownloadOutlined } from '@ant-design/icons';
import KernelConfigForm from '../../components/KernelConfigForm'
import ProCard from '@ant-design/pro-card';
import CompoundedSpace from 'antd/lib/space';

const { Divider } = ProCard;


const originData = [];
const OSTypeConfigList = React.forwardRef((props, ref) => {
  const intl = useIntl();
  const oslistRef = useRef();
  const [readonlyone, setReadonlyOne] = useState(false);
  const [count, setCount] = useState(0);
  const onPostTask = () => {
    oslistRef.current.reload();
  }
  const KernelConfigChange = (e) => {
    setReadonlyOne(e);
  }
  
  const handleDelOSType = async (record) => {
    const hide = message.loading(intl.formatMessage({
      id: 'pages.hotfix.deleting',
      defaultMessage: 'Now deleting'
    }));
    const token = localStorage.getItem('token');
    try {
        let res = await delOSType(record.id, token);
        hide();
        if (res.code == 200) {
            message.success(intl.formatMessage({
              id:'pages.hotfix.delete_success',
              defaultMessage:'Delete Success'
            }));
            getOSTypeList();
            return true;
        } else {
            message.error(`${intl.formatMessage({id:'pages.hotfix.delete_failed', defaultMessage:'Delete Failed'})}: ${res.message}`);
            return false;
        }
    } catch (error) {
        hide();
        return false;
    }
  }

  const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    const inputNode = inputType === 'number' ? <InputNumber /> : <ProFormText />;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={[
              {
                required: true,
                message: `Please Input ${title}!`,
              },
            ]}
          >
            {inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };
  const [form] = Form.useForm();
  const [data, setData] = useState(originData);
  const [editingKey, setEditingKey] = useState('');
  const isEditing = (record) => record.id === editingKey;
  const edit = (record) => {
    console.log(record,"edit",record.id);
    form.setFieldsValue({
      os_type: '',
      source_repo: '',
      image: '',
      source_devel: '',
      source_debuginfo: '',
      ...record,
    });
    setEditingKey(record.id);
  };
  const cancel = () => {
    setEditingKey('');
  };
  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);
      const Poldata = {
        id: key.id,
        os_type: row.os_type,
        source_repo: row.source_repo,
        image:row.image,
        source_devel: row.source_devel,
        source_debuginfo: row.source_debuginfo
      }
      postChangeOsType(Poldata).then(res => {
        if(res.code === 200){
          const item = newData[index];
          newData.splice(index, 1, {
            ...item,
            ...row,
          });
          setData(newData);
          setEditingKey('');
          message.success(intl.formatMessage({
            id:'pages.hotfix.submit_success',
            defaultMessage:'Submit success'
          }));
          oslistRef.current.reload();
        }
      }).catch(err => {
        console.log(err);
      });
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };
  const columns = [
    {
      title: <FormattedMessage id="pages.hotfix.os_type" defaultMessage="os_type"/>,
      dataIndex: 'os_type',
      key: 'os_type',
      width: 100,
      ellipsis: true,
      editable: true,
      tooltip: intl.formatMessage({
        id: 'pages.hotfix.tooltips.os_type',
        defaultMessage:'Please name your Operating System. eg, Anolis for Anolis Operating System',
    }),
    },
    {
      title: <FormattedMessage id="pages.hotfix.kernel_repo_git" defaultMessage="repo_location" />,
      dataIndex: 'source_repo',
      valueType: 'input',
      editable: true,
      tooltip: intl.formatMessage({
        id: 'pages.hotfix.tooltips.repo_address',
        defaultMessage: 'The code repo of your os',
      })
    },
    {
      title: <FormattedMessage id="pages.hotfix.image" defaultMessage="image" />,
      dataIndex: 'image',
      valueType: 'input',
      editable: true,
      tooltip: intl.formatMessage({
        id: 'pages.hotfix.tooltips.building_image',
        defaultMessage: 'Please input the building image when building hotfix of this os',
      })
    },
    {
      title: <FormattedMessage id="pages.hotfix.version_repo_devel" defaultMessage="devel warehouse address" />,
      dataIndex: 'source_devel',
      valueType: 'input',
      editable: true,
    },
    {
      title: <FormattedMessage id="pages.hotfix.version_repo_debuginfo" defaultMessage="debuginfo Warehouse address" />,
      dataIndex: 'source_debuginfo',
      valueType: 'input',
      editable: true,
    },
    {
      title: <FormattedMessage id="pages.hotfix.synch_information" defaultMessage="Synchronous information" />,
      dataIndex: 'sync_status',
      valueType: 'input',
      width: 180,
      render: (_, record) => {
        if(record.sync_status === 2){
          return <><Tag color="green">{intl.formatMessage({id:'pages.hotfix.sync_status.success', defaultMessage:'Kernel sync success'})}</Tag><br />{record.sync_at}</>
        }else if(record.sync_status === 1){
          return <><Tag color="red">{intl.formatMessage({id:'pages.hotfix.sync_status.failed', defaultMessage:'Kernel sync failed'})}</Tag><br />{record.sync_at}</>
        }else if(record.sync_status === 0){
          return <><Tag color="blue">{intl.formatMessage({id:'pages.hotfix.sync_status.synchronizing', defaultMessage:'Kernel synchronizing'})}</Tag><br />{record.sync_at}</>
        }else{
          return <>-</>
        }
      }
    },
    {
      title: <FormattedMessage id="pages.hotfix.operation" defaultMessage="Operating" />,
      key: 'option',
      dataIndex: 'option',
      width: 160,
      valueType: 'option',
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record)}
              style={{
                marginRight: 8,
              }}
            >
              {intl.formatMessage({id: 'pages.hotfix.save', defaultMessage:'Save'})}
            </Typography.Link>
            <Popconfirm title={intl.formatMessage({id:'pages.hotfix.confirm.cancel', defaultMessage:'Are you sure to cancel?'})} onConfirm={cancel}>
              <a>{intl.formatMessage({id:'pages.hotfix.cancel', defaultMessage:'Cancel'})}</a>
            </Popconfirm>
          </span>
        ) : (
          <span>
            <Typography.Link disabled={record.sync_status === 0 ? true : false} onClick={async () => {
                if(record.sync_status === 0){
                  return false;
                }else{
                  await PostWhetherSyncRequest(record.id);
                  oslistRef.current.reload();
                }
              }}>
                <FormattedMessage id="pages.hotfix.synchronization" defaultMessage="Synchronization" />
            </Typography.Link>
            <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)} style={{
                marginRight: 8,
                marginLeft: 8,
              }}>
              {intl.formatMessage({id:'pages.hotfix.edit', defaultMessage:'Edit'})}
            </Typography.Link>
            <Popconfirm title={intl.formatMessage({id:'pages.hotfix.confirm.delete_ostype', defaultMessage:'Sure to delete this type?Attention,deleting this type will delete all kernel version related to this type!'})}
             disabled={record.sync_status === 0 ? true : false} onConfirm={async () => {
                if (record.id == undefined) {
                    message.error(intl.formatMessage({
                        id: 'pages.hotfix.delete_ostype_not_exist',
                        defaultMessage: "Not allow to delete this os type"
                    }))
                } else {
                    await handleDelOSType(record);
                    oslistRef.current.reload();
                }
              }}>
                  <a disabled={record.sync_status === 0 ? true : false}><FormattedMessage id="pages.hotfix.delete" defaultMessage="OS_type delete" /></a>
              </Popconfirm>
          </span>
        );
      }
    }
  ];
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.valueType,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  return (
    <>
      <KernelConfigForm onSuccess={onPostTask} />
      <Divider />
      <Form form={form} component={false}>
        <ProTable
          headerTitle={intl.formatMessage({
            id: 'pages.hotfix.title.os_type',
            defaultMessage: 'os_type conf',
          })}
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          rowClassName="editable-row"
          search={false}
          actionRef={oslistRef}
          rowKey="id"
          toolBarRender={() => [
          ]}
          request={getOSTypeList}
          columns={mergedColumns}
          pagination={{
            onChange: cancel,
          }}
        />
      </Form>
      {/* <ProTable
        headerTitle={intl.formatMessage({
          id: 'pages.hotfix.title.os_type',
          defaultMessage: 'os_type conf',
        })}
        actionRef={oslistRef}
        rowKey="id"
        search={false}
        toolBarRender={() => [
        ]}
        request={getOSTypeList}
        columns={columns}
      /> */}
    </>
  );
});

export default OSTypeConfigList;